
/****************************************************************************/
/*Copyright (c) 2011, Florent DEVILLE.                                      */
/*All rights reserved.                                                      */
/*                                                                          */
/*Redistribution and use in source and binary forms, with or without        */
/*modification, are permitted provided that the following conditions        */
/*are met:                                                                  */
/*                                                                          */
/* - Redistributions of source code must retain the above copyright         */
/*notice, this list of conditions and the following disclaimer.             */
/* - Redistributions in binary form must reproduce the above                */
/*copyright notice, this list of conditions and the following               */
/*disclaimer in the documentation and/or other materials provided           */
/*with the distribution.                                                    */
/* - The names of its contributors cannot be used to endorse or promote     */
/*products derived from this software without specific prior written        */
/*permission.                                                               */
/* - The source code cannot be used for commercial purposes without         */ 
/*its contributors' permission.                                             */
/*                                                                          */
/*THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS       */
/*"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT         */
/*LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS         */
/*FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE            */
/*COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,       */
/*INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,      */
/*BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;          */
/*LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER          */
/*CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT        */
/*LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN         */
/*ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE           */
/*POSSIBILITY OF SUCH DAMAGE.                                               */
/****************************************************************************/

#include "RTScene.h"
#include "RTIPrimitive.h"
#include "RTILight.h"
#include "RTIProcTexture.h"
#include "RTTexture.h"
#include "RTMaterial.h"

#include <limits>
#include <algorithm>

namespace RT
{
	/*Initialise the singleton variable*/
	RTScene* RTScene::m_instance = 0;

	/*Constructor*/
	RTScene::RTScene():m_primitives(), m_lights(), m_materials(), m_textures(), 
		m_globalAmbientLight(0.1f, 0.1f, 0.1f, 1)
	{}

	/*Destructor*/
	RTScene::~RTScene()
	{
		for(vector<RTIPrimitive*>::iterator i = m_primitives.begin(); i != m_primitives.end(); i++)
		{
			delete *i;
		}

		for(vector<RTILight*>::iterator i = m_lights.begin(); i != m_lights.end(); i++)
		{
			delete *i;
		}

		for(map<string, RTMaterial*>::iterator i = m_materials.begin(); i != m_materials.end(); i++)
		{
			delete (*i).second;
		}

		for(vector<RTIProcTexture*>::iterator i = m_textures.begin(); i != m_textures.end(); i++)
		{
			delete *i;
		}

		for(vector<RTTexture*>::iterator i = m_fileTexture.begin(); i != m_fileTexture.end(); i++)
		{
			delete *i;
		}
	}

	/*Return the singleton*/
	RTScene& RTScene::getInstance()
	{
		if(m_instance == 0)
			m_instance = new RTScene();

		return *m_instance;
	}

	/*Close the singleton*/
	void RTScene::close()
	{
		if(m_instance != 0)
		{
			delete m_instance;
			m_instance = 0;
		}
	}

	/*Return a primitive*/
	RTIPrimitive* RTScene::getPrimitive(I32 index)const
	{
		return m_primitives[index];
	}

	/*Return a material*/
	RTMaterial* RTScene::getMaterial(const string& materialName)const
	{
		map<string, RTMaterial*>::const_iterator i = m_materials.find(materialName);
		if(i == m_materials.end())
			return 0;

		return (*i).second;
	}

	//Return the light with the index id. Return 0 if the index is out of range.
	RTILight* RTScene::getLight(U32 id)const
	{
		//check if the index is inside range
		if(id < 0 || id >= m_lights.size())
			return 0;

		//return the light poI32er.
		return m_lights[id];
	}

	/*Delete a primitive*/
	RTIPrimitive* RTScene::removePrimitive(I32 index)
	{
		//get the RTPrimitive
		vector<RTIPrimitive*>::iterator i = m_primitives.begin();
		std::advance(i, index);
		RTIPrimitive* p = *i;

		//erase it
		m_primitives.erase(i);

		//return the RTPrimitive
		return p;
	}

	//Test collision between a ray and the scene.
	//Returns the id and the distance between the ray origin and the first RTPrimitive.
	//If the ray doesn't intersect with any RTPrimitive, i return -1.
	I32 RTScene::getFirstCollision(const RTRay& ray, F32& dist)
	{
		//F32 min_dist = std::numeric_limits<F32>::max(0, 0);
		F32 min_dist = -1;
		I32 min_RTPrimitive = -1;

		for(vector<RTIPrimitive*>::iterator i = m_primitives.begin(); i != m_primitives.end(); i++)
		{
			F32 dist;
			bool test = (*i)->intersect(ray, dist, false);
			if((test && dist < min_dist && dist > 0.01f) ||(test && min_dist == -1 && dist > 0.01f))
			{
				min_RTPrimitive = i - m_primitives.begin();
				min_dist = dist;
			}
		}

		if(min_RTPrimitive == -1)
			return -1;

		dist = min_dist;
		return min_RTPrimitive;
	}

	/*Add a primitive to the scene*/
	bool RTScene::addPrimitive(RTIPrimitive* primitive)
	{
		if(std::find(m_primitives.begin(), m_primitives.end(), primitive) != m_primitives.end())
			return false;

		m_primitives.push_back(primitive);
		return true;
	}

	/*Add a light to the scene*/
	bool RTScene::addLight(RTILight* light)
	{
		if(std::find(m_lights.begin(), m_lights.end(), light) != m_lights.end())
			return false;

		m_lights.push_back(light);
		return true;
	}

	/*Add a material to the scene*/
	bool RTScene::addMaterial(RTMaterial* material, const string& matName)
	{
		if(m_materials.find(matName) != m_materials.end())
			return false;

		m_materials.insert ( pair<string, RTMaterial*>(matName, material) );
		return true;
	}

	/*Add a procedural texture to the scene*/
	bool RTScene::addProcTexture(RTIProcTexture* texture)
	{
		if(std::find(m_textures.begin(), m_textures.end(), texture) != m_textures.end())
			return false;

		m_textures.push_back(texture);
		return true;
	}

	//store a texture coming from a file
	bool RTScene::addFileTexture(RTTexture* texture)
	{
		if(std::find(m_fileTexture.begin(), m_fileTexture.end(), texture) != m_fileTexture.end())
			return false;

		m_fileTexture.push_back(texture);
		return true;
	}
	//
	//const RTColor RTScene::computeLightColor(const RTVector3f& view, const RTPoint3f& center, const RTNormal3f& normal,
	//											 const RTIPrimitive& p)
	//{
	//	//intersection poI32 in local coordinates
	//	RTVector3f I32erLC;
	//
	//	//get material
	//	RTMaterial* caracteristics = p.getMaterial();
	//	RTColor t_color(0, 0, 0);
	//
	//	//go throught all the lights
	//	for(vector<RTILight*>::iterator i = m_lights.begin(); i != m_lights.end(); i++)
	//	{
	//		//compute the shadow ray
	//		RTRay shadowRay;
	//		F32 lightDistance = -1;
	//		(*i)->computeShadowRay(center, shadowRay, &lightDistance);
	//		
	//		//calculate the intersection poI32 in the local coordinate
	//		I32erLC = center * p.getInverseWorldViewMatrix();
	//
	//		//check if there is something between the object and the light
	//		if(!testCollision(shadowRay, lightDistance)) //no collision
	//		{
	//			//get the light color and light direction vector
	//			RTColor lightColor = (*i)->computeColor(shadowRay, lightDistance);
	//			RTVector3f L = shadowRay.getDirection();
	//
	//			//LAMBERT
	//			F32 LdotN = L.dot(normal); 
	//			if(LdotN > 0.f)
	//			{
	//				t_color += lightColor * caracteristics->getDiffuse(I32erLC, p)*LdotN;
	//				
	//				//PHONG
	//				if((*i)->getLightType() == eDirectionalLight)
	//					continue;
	//				RTVector3f lightReflection = L - (normal * 2.0f * LdotN);
	//				F32 dot = view.dot(lightReflection); 
	//				if(dot > 0.f)
	//					t_color += lightColor * powf(dot, caracteristics->m_shininess)*caracteristics->m_specular;
	//
	//				//BLINN PHONG
	//				/*RTVector3f H = L + view;
	//				H.normalize();
	//				F32 NdotH = normal.dot(H);
	//				if(NdotH > 0.f)
	//					t_color += (*i)->getColor()*powf(NdotH, caracteristics.m_shininess)*caracteristics.m_specular;*/
	//			}
	//		}
	//	}
	//	
	//	//AMBIENT
	//	if(caracteristics->useBumpMapping())
	//		t_color += normal*caracteristics->getAmbient(I32erLC)*0.1f;
	//	else
	//		t_color += caracteristics->getAmbient(I32erLC)*0.1f;
	//
	//	//saturate (between 0 and 1)
	//	t_color.saturate();
	//
	//	return t_color;
	//}
	//
	//const RTColor RTScene::computeLightColorV2(const RTVector3f& view, const RTPoint3f& center, const RTNormal3f& normal,  
	//	const RTIPrimitive& RTPrimitive, const RTColor& input)
	//{
	//	//intersection poI32 in local coordinates
	//	RTVector3f I32erLC;
	//
	//	RTColor t_color(0, 0, 0);
	//	//get material
	//	RTMaterial* caracteristics = RTPrimitive.getMaterial();
	//
	//	//go throught all the lights
	//	for(vector<RTILight*>::iterator i = m_lights.begin(); i != m_lights.end(); i++)
	//	{
	//		//compute the shadow ray
	//		RTRay shadowRay;
	//		F32 lightDistance = -1;
	//		(*i)->computeShadowRay(center, shadowRay, &lightDistance);
	//		
	//		//calculate the intersection poI32 in the local coordinate
	//		I32erLC = center * RTPrimitive.getInverseWorldViewMatrix();
	//
	//		//check if there is something between the object and the light
	//		if(!testCollision(shadowRay, lightDistance)) //no collision
	//		{
	//			//get the light color and light direction vector
	//			RTColor lightColor = (*i)->computeColor(shadowRay, lightDistance);
	//			RTVector3f L = shadowRay.getDirection();
	//
	//			//LAMBERT
	//			F32 LdotN = L.dot(normal); 
	//			if(LdotN > 0.f)
	//			{
	//				//t_color += lightColor * caracteristics->getDiffuse(I32erLC, p)*LdotN;
	//				t_color += lightColor * input * LdotN;
	//				
	//				//PHONG
	//				if((*i)->getLightType() == eDirectionalLight)
	//					continue;
	//				RTVector3f lightReflection = L - (normal * 2.0f * LdotN);
	//				F32 dot = view.dot(lightReflection); 
	//				if(dot > 0.f)
	//					t_color += lightColor * powf(dot, caracteristics->m_shininess)*caracteristics->m_specular;
	//
	//				//BLINN PHONG
	//				/*RTVector3f H = L + view;
	//				H.normalize();
	//				F32 NdotH = normal.dot(H);
	//				if(NdotH > 0.f)
	//					t_color += (*i)->getColor()*powf(NdotH, caracteristics.m_shininess)*caracteristics.m_specular;*/
	//			}
	//		}
	//	}
	//	
	//	//AMBIENT
	//	if(caracteristics->useBumpMapping())
	//		t_color += normal*caracteristics->getAmbient(I32erLC)*0.1f;
	//	else
	//		t_color += caracteristics->getAmbient(I32erLC)*0.1f;
	//
	//	//saturate (between 0 and 1)
	//	t_color.saturate();
	//
	//	return t_color;
	//}


	//Test if the ray collide with a RTPrimitive in the scene. 
	//dist is the length of the ray. A negative number means an infinite length.
	//return true if it collide or false if no collision is detected		
	bool RTScene::testCollision(const RTRay& ray, F32 dist)
	{
		for(vector<RTIPrimitive*>::iterator i = m_primitives.begin(); i != m_primitives.end(); i++)
		{
			F32 t_dist;
			bool test = (*i)->intersect(ray, t_dist, false);

			if(!test)
				continue;

			if(dist <= 0)
			{
				//if(t_dist>0.1f)//if there is something between 0.01 and infinity
					return true;
			}
			else
			{
				if(t_dist>0.1f && t_dist<dist)//if there is something between 0.01 and dist
					return true;
			}
		}
		return false;
	}

	/*Apply the view matrix to the scene*/
	void RTScene::applyViewMatrix(const RTMatrix44& view)
	{
		for(vector<RTIPrimitive*>::iterator i = m_primitives.begin(); i != m_primitives.end(); i++)
			(*i)->applyViewMatrix(view);

		for(vector<RTILight*>::iterator i = m_lights.begin(); i != m_lights.end(); i++)
			(*i)->applyViewMatrix(view);
	}

	//Return the number of source lights in the scene
	U32 RTScene::getNumberOfLights()const
	{
		return m_lights.size();
	}

	//set the scene global ambient light
	void RTScene::setGlobalAmbientLight(const RTColor& gal)
	{
		m_globalAmbientLight = gal;
	}

	//get the scene global ambient light
	RTColor RTScene::getGlobalAmbientLight()const
	{
		return m_globalAmbientLight;
	}

}